package com.jf3q.front.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jf3q.common.domain.EduMember;
import com.jf3q.common.utils.JwtTokenUtil;
import com.jf3q.common.utils.SaltPassUtils;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.front.dto.MemberLoginDto;
import com.jf3q.front.dto.MemberRegDto;
import com.jf3q.front.service.MemberService;
import com.jf3q.front.vo.LoginSuccessVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/member")
@Tag(name = "会员控制层")
public class MemberController {
    @Autowired
    MemberService memberService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @PostMapping("/reg")
    @Operation(summary = "会员注册")
    public ResultVo reg(@RequestBody MemberRegDto memberRegDto){

        //校验各种
        memberService.reg(memberRegDto);
        return ResultVo.success();

    }


    @PostMapping("/login")
    @Operation(summary = "会员登陆")
    public ResultVo login(@RequestBody MemberLoginDto memberLoginDto){

        //.trim()把空格去掉
        if (StringUtils.isEmpty(memberLoginDto.getMobile().trim())) {
            return ResultVo.error("手机号必填");
        }else if (StringUtils.isEmpty(memberLoginDto.getPassword())) {
            return ResultVo.error("密码必填");
        }else{
            LambdaQueryWrapper<EduMember> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EduMember::getMobile, memberLoginDto.getMobile());
            EduMember member = memberService.getOne(queryWrapper);
            if(ObjectUtils.isEmpty(member)){
                return ResultVo.error("账号不存在");
            }
            if(member.getIsDisabled()){
                return ResultVo.error("账号已被禁用");
            }

            //校验密码是否正确（这里做了加盐加密）
            if (!SaltPassUtils.PasswordValidation(member.getSalt(),memberLoginDto.getPassword(),member.getPassword())) {
                return ResultVo.error("密码错误");
            }

            //生成token返回给前端
            String token = jwtTokenUtil.getToken(member.getMobile());

            //把token和个人基本信息返回给前端
            //把敏感信息置空
//            member.setPassword(null);
//            member.setSalt(null);
            return ResultVo.success( new LoginSuccessVo(token,member));

        }


    }


}
